﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Optimization;
using System.Web.Security;
using System.Web.Script.Serialization;
using CMS.Utils;
using CMS.Services;
using CMS.UI.Common.Validation;
using CMS.Utils.Diagnostics;

namespace CMS.UI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredIfValidator));
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            String requestedUrl = HttpContext.Current.Request.Url.AbsolutePath;
            if (requestedUrl != "/" && requestedUrl.EndsWith("/"))
                Response.RedirectPermanent(requestedUrl.TrimEnd('/'), true);
        }

        protected void Application_error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            if (exception is HttpException)
            {
               
                Log.Info(String.Format("404 {0}",  Request.Url.AbsolutePath), exception);
            }
            else
            {
                Log.Error("Application error", exception);
            }
        }
    }
}